<template>
  <div>
    <!--顶部卡片-->
    <el-card>
      <Category :scene="scene"/>
    </el-card>


    <!--下部卡片-->
    <el-card style="margin: 10px 0">
      <div v-show="scene==0">
        <el-button type="primary" icon="Plus" :disabled="!CategoryStore.c3Id" @click="addAttr">添加属性</el-button>
        <el-table border style="margin: 10px 0" stripe :data="attrArr">
          <el-table-column label="序号" type="index" align="center" width="80px"></el-table-column>
          <el-table-column label="属性名称" width="120px" prop="attrName"></el-table-column>
          <el-table-column label="属性值名称">
            <template #="{row}">
              <el-tag style="margin:5px" v-for="(item) in row.attrValueList" :key="item.id">
                {{ item.valueName }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="120px">
            <template #="{row}">
              <!--修改已有数据的按扭-->
              <el-button type="primary" size="small" icon="Edit" @click="updateAttr(row)"></el-button>
              <!--删除已有属性-->
              <el-popconfirm :title="`你确定要删除${row.attrName}？`" width="200px" @confirm="deleteAttr(row.id)">
                <template #reference>
                  <el-button type="danger" size="small" icon="Delete"></el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div v-show="scene==1">
        <!--展示添加属性与修改数据的解构-->
        <el-form model="attrParams">
          <el-form-item label="属性名称">
            <el-input placeholder="请输入属性名称" style="width: 50%" v-model="attrParams.attrName"></el-input>
          </el-form-item>
          <el-button type="primary" size="default" icon="Plus" @click="addAttrValue"
                     :disabled="attrParams.attrName.trim()==''">
            添加属性
          </el-button>
          <el-button type="danger" size="default" @click="cancel">取消</el-button>
          <el-table border stripe style="margin: 10px 0" :data="attrParams.attrValueList">
            <el-table-column width="80px" label="序号" type="index" align="center"></el-table-column>
            <el-table-column label="属性值名称">
              <!--row即为当前的属性值对象-->
              <template #="{row,$index}">
                <el-input :ref="(vc:any)=>inputArr[$index]=vc" v-if="row.flag" @blur="toLook(row,$index)"
                          placeholder="请输入属性值名称"
                          v-model="row.valueName"></el-input>
                <div v-else @click="toEdit(row,$index)">{{ row.valueName }}</div>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template #="{$index}">
                <el-button type="danger" size="small" icon="Delete"
                           @click="attrParams.attrValueList.splice($index,1)"></el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-button type="primary" size="default" @click="save"
                     :disabled="attrParams.attrValueList.length==0||attrParams.attrName.trim()==''">保存
          </el-button>
          <el-button type="danger" size="default" @click="cancel">取消</el-button>
        </el-form>
      </div>


    </el-card>

  </div>
</template>

<script setup lang="ts">
//watch
import {watch, ref, reactive, nextTick, onBeforeUnmount} from "vue";
//@ts-ignore
import useCategoryStore from "@/piniaStore/moudules/categoryStore.ts";
//@ts-ignore
import {T_Attr, T_AttrResponseData, T_AttrValue} from "@/api/product/attr/type.ts";
import {ElMessage} from "element-plus";

//获取仓库
const CategoryStore = useCategoryStore();
//存储返回的数据
let attrArr = ref<T_Attr[]>([]);
//定义card组件内容切换的变量
let scene = ref<number>(0);//如果是scene：0：显示table  ，scene=1，显示修改增加属性
//收集新增的属性数据
let attrParams = reactive<T_Attr>({
  attrName: "",//新增属性的名字
  attrValueList: [],//新增的属性值数组
  categoryId: "",//三级分类的ID
  categoryLevel: 3//代表三级分类
})

//准备一个数组：存储对应的组件实例：el-input
let inputArr = ref<any>([]);

//监听仓库三级分类ID变化，有三级分类ID就发送请求
watch(() => CategoryStore.c3Id, async () => {
  //清空上一次查询的数据
  attrArr.value = [];
  //保证三级分类有才能发请求
  if (!CategoryStore.c3Id) return;
  //通知仓库去拿数据
  attrArr.value = await CategoryStore.getAttrs();
});

//添加属性的时间回调
const addAttr = () => {
  //清空数据,收集三级分类id
  attrParams.attrName = "";
  attrParams.attrValueList = [];
  attrParams.categoryId = CategoryStore.c3Id;
  //切换卡片
  scene.value = 1;
};

//修改表格属性按扭的回调
const updateAttr = (row: T_Attr) => {
  scene.value = 1;
  //展示当前数据将row的数据赋值给attrParams
  //Object.assign(attrParams, row);// 浅拷贝，内存中指向的是同一个对象
  Object.assign(attrParams, JSON.parse(JSON.stringify(row)));// 深拷贝，


};

//取消按扭的回调
const cancel = () => {
  scene.value = 0;

};

//添加属性值按扭的回调
const addAttrValue = () => {
  //点击添加属性值按扭，向数组添加一个属性值对象
  attrParams.attrValueList.push({
    valueName: '',
    flag: true,//控制每个属性的编辑模式/查看模式的切换
  });
  //获取最后的el-input组件聚焦
  nextTick(() => {
    inputArr.value[attrParams.attrValueList.length - 1].focus();
  })
}

//保存按扭的回调
const save = async () => {
  //通知仓库发送请求
  try {
    await CategoryStore.addOrupdateAttr(attrParams);
    ElMessage({
      type: "success",
      message: attrParams.id ? "修改成功" : "添加成功"
    })
  } catch (error) {
    ElMessage({
      type: "error",
      message: (error as Error).message
    })
  } finally {
    scene.value = 0;
    //重新获取一次请求,更新表格数据
    attrArr.value = await CategoryStore.getAttrs();
  }
}

//属性值，编辑模式/查看模式切换
const toLook = (row: T_AttrValue, $index: number) => {
  //非法清空判断
  if (row.valueName.trim() == '') {
    //删除掉属性值为空的元素
    attrParams.attrValueList.splice($index, 1);
    //提示信息
    ElMessage({
      type: 'error',
      message: '属性值不能为空'
    })
    return;
  }
  //非法情况2：不重复
  let repeat = attrParams.attrValueList.find((item: T_AttrValue) => {
    if (item != row) {//不能跟自己比
      return item.valueName === row.valueName;
    }
  })
  if (repeat) {
    attrParams.attrValueList.splice($index, 1); //将重复的属性值从数组中删除
    //提示信息
    ElMessage({
      type: 'error',
      message: '属性值不能重复'
    })
    return;
  }
  row.flag = false;//展示div
}

//div->编辑模式回调
const toEdit = (row: T_AttrValue, $index: number) => {
  row.flag = true;//切回编辑模式
  //nextTick:响应式数据发生变化，获取更新的Dom组件实例
  nextTick(() => {
    inputArr.value[$index].focus();
  })

}

//删除属性回调
const deleteAttr = async (id: number) => {
  try {
    await CategoryStore.removeAttrById(id)
    ElMessage({
      type: 'success',
      message: "删除成功"
    })
  } catch (error) {
    ElMessage({
      type: 'error',
      message: (error as Error).message
    })
  }
  //再获取一下数据
  //重新获取一次请求,更新表格数据
  attrArr.value = await CategoryStore.getAttrs();
}

//路由组件销毁的时候，把仓库分类相关的数据清空
onBeforeUnmount(() => {
  CategoryStore.$reset();
})


</script>

<style scoped>

</style>